package com.doeis.common.utils;


import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;

public class StringUtils {
	
	public static boolean isBlank(String s){
		return s==null || s.trim().length()<1;
	}
	
	public static boolean isBlank(List list){
		return list == null || list.size()<=0;
	}
	
	public static String showValue(String string){
		if(null == string || "".equals(string)){
			return "-";
		}else{
			return string;
		}
	}
	
	public static Object showValue(Object o){
		if(null == o){
			return "-";
		}else{
			return o;
		}
	}
	
	/**
	 * 截取字符串text中前len个字母或者汉字,以defaultChar结尾
	 * @param text
	 * @param escape 是否过滤html字符
	 * @param len
	 * @param defaultChar
	 * @return
	 */
	public static String simplifyString(String text, Boolean escape, Integer len, String defaultChar){
		if(len == null){
			len = 10;
		}
		
		if(isBlank(defaultChar)){
			defaultChar = "...";
		}
		
		if(escape){
			text = text.replaceAll("<[^>]*>","");
		}
		
		int textLength = text.length();
		String str = "";
		if(textLength >= len){
			str = text.substring(0, len) + defaultChar;
		}else{
			str = text;
		}
		
		return str;
	}

	/**
	 * 过滤HTML tag
	 * @param string
	 * @return
	 */
	public static String escapeHTML(String string){
		if(isBlank(string)){
			return "";
		}
		return string.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("\n", "<br/>").replaceAll("\"", "&quot;");
	}
	
	public static String deleteHTML(String html){
		if(isBlank(html)){
			return "";
		}
		return html.replaceAll("<[^>]*>", "");
	}
	
	/**  
     * 获得随机数字符串（fangdo get from google......）  
     *   
     * @param length  需要获得随机数的长度  
     * 
     * @param type 随机数的类型：
     * 			'0':表示仅获得数字随机数；
     * 			'1'：表示仅获得字符随机数；
     * 			'2'：表示获得数字字符混合随机数  
     * 
     * @return  
     */  
    public static String generateRandomCode(int length, int type) {   
        // 随机字符串   
        String strRandom = "";   
  
        Random rnd = new Random();   
  
        if (length < 0) {   
            length = 5;   
        }   
  
        if ((type > 2) || (type < 0)) {   
            type = 2;   
        }   
  
        switch (type) {   
	        case 0:   
	            for (int iLoop = 0; iLoop < length; iLoop++) {   
	                strRandom += Integer.toString(rnd.nextInt(10));   
	            }   
	            break;   
	        case 1:   
	            for (int iLoop = 0; iLoop < length; iLoop++) {   
	                strRandom += Integer.toString((35 - rnd.nextInt(10)), 36);   
	            }   
	            break;   
	        case 2:   
	            for (int iLoop = 0; iLoop < length; iLoop++) {   
	                strRandom += Integer.toString(rnd.nextInt(36), 36);   
	            }   
	            break;   
        }   
           
        return strRandom;   
    }
    
    public static List<String> strToList(String s,String split){
    	if(isBlank(s))
    		return null;
    	
    	ArrayList<String> r = new ArrayList<String>();
    	String[] t = s.split(split);
    	for(String m: t){
    		r.add(m);
    	}
    	return r;
    }
    
    
    
    public static List<String> strToList(String s){
    	return strToList(s,",");
    }
    
    public static String arrayToString(Integer[] values){
    	if(values != null && values.length>0){
    		StringBuffer sb = new StringBuffer();
    		for(Integer v : values){
    			sb.append(v.intValue()+",");
    		}
    		return sb.substring(0, sb.length()-1);
    	}
    	return null;
    }
    
    public static String arrayToString(String[] values){
    	if(values != null && values.length>0){
    		StringBuffer sb = new StringBuffer();
    		for(String v : values){
    			sb.append(v+",");
    		}
    		return sb.substring(0, sb.length()-1);
    	}
    	return null;
    }
    
    public static String[] strToArray(String s){
    	return strToArray(s,",");
    }
    public static String[] strToArray(String s,String split){
    	if(isBlank(s))
    		return null;
    	return s.split(split);
    }
    
    public static int[] strToIntArray(String s){
		String[] codes = strToArray(s, ",");
		int keys[] = new int[codes.length];;
		for(int i=0;i<codes.length;i++){
			keys[i] = Integer.valueOf(codes[i]).intValue();
		}	
		return keys;
    }
    public static String listToStr(List<String> list){
    	StringBuffer sb = new StringBuffer();
    	if(list != null && list.size()>0){
	    	for(String item: list){
	    		sb.append(item+",");
			}
	    	return sb.substring(0, sb.length()-1);
    	}
    	return null;
    }
    
    public static String listToStr(List<String> list, String splitStr){
    	StringBuffer sb = new StringBuffer();
    	if(list != null && list.size()>0){
	    	for(String item: list){
	    		sb.append(item + splitStr);
			}
	    	return sb.substring(0, sb.length()-1);
    	}
    	return null;
    }
    
    public static String collectionToString(Collection<String> coll){
    	StringBuffer sb = new StringBuffer();
    	if(coll != null && coll.size()>0){
	    	for(String item: coll){
	    		sb.append(item+",");
			}
	    	return sb.substring(0, sb.length()-1);
    	}
    	return null;
    }
    
    /**
	 * 以一种简单的方式格式化字符串
	 * 如  String s = StringHelper.format("{0} is {1}", "apple", "fruit");
	 * System.out.println(s);	//输出  apple is fruit.
	 * @param pattern
	 * @param args
	 * @return
	 */
	public static String format(String pattern, Object ...args){
		for(int i=0; i<args.length; i++) {
			pattern = pattern.replace("{"+i+"}", args[i].toString().trim());
		}
		return pattern;
	}
	
	/**
	 * 校验邮箱是否合法
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email){
		if(isBlank(email)){
			return false;
		}
		
		String check = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	    Pattern regex = Pattern.compile(check);
	    Matcher matcher = regex.matcher(email);
        return matcher.matches();
	}
	
	/**
	 * 校验密码
	 * 	只能包含 字母、数字和.!@#$%^&*+-_等特殊字符，长度限定为6-16位。
	 * @param pwd
	 * @return
	 */
	public static boolean isPassword(String pwd){
		String check = "^[a-zA-Z0-9.!@#$%^&*+-_]{6,16}$";
	    Pattern regex = Pattern.compile(check);
	    Matcher matcher = regex.matcher(pwd);
        return matcher.matches();
	}
	
	/**
	 * 校验网机号
	 * @param phoneid
	 * @return
	 */
	public static boolean isPhoneid(String phoneid){
		if(isBlank(phoneid)) 
			return false;
		//匹配总机,以#分隔的分机,及以#开头的分机
		String check = "^[1-9]\\d{4,10}|[1-9]\\d{4,10}#[1-9]\\d{0,3}|#[1-9]\\d{4,10}";
	    Pattern regex = Pattern.compile(check);
	    Matcher matcher = regex.matcher(phoneid.trim());
        return matcher.matches();		
	}
	
	public static boolean isSubPhoneid(String subPhoneid){
		if(subPhoneid == null) {
			return false;
		}
				
		String check = "^[1-9]\\d{4,10}#[1-9]\\d{0,3}|#[1-9]\\d{4,10}$";
	    Pattern regex = Pattern.compile(check);
	    Matcher matcher = regex.matcher(subPhoneid.trim());
	    return matcher.matches();	
	}
	
	/**
	 * 校验组机号
	 * @param searchPhoneid
	 * @return
	 */
	public static boolean isGroupid(String groupid){
		if(groupid == null) {
			return false;
		}		
		String check = "^\\*[1-9]\\d{4,15}$";
	    Pattern regex = Pattern.compile(check);
	    Matcher matcher = regex.matcher(groupid.trim());
        return matcher.matches();		
	}
	
	public static boolean isAHref(String href){
		if(isBlank(href))
			return false;
		
		String regExp= "<a href='(.*)'>(.*)</a>";
		Pattern regex = Pattern.compile(regExp);
	    Matcher matcher = regex.matcher(href);
        return matcher.matches();
	}
	
	public static String sortListToString(List<String> keys){
		if( keys == null )
			return null;
		
		HashMap<String, String> tmp = new HashMap<String, String>();
		for(String key : keys){
			tmp.put(key, key);
		}
		return collectionToString(tmp.values());
	}
	
	/**
	 * 
	 * 按照指定的size，分割objectlist成若干个子list放到returnList中返回
	 * @param <E>
	 * 
	 * @param size
	 * @param list
	 * @return
	 */
	public static <E> List<List<E>> subList(Integer size, List<E> list){
		
		//若size为null,给一个 默认值
		if(null == size){
			size = 5;
		}
		
		//统计循环的次数
		int j=0;// 步长
		int listSize = list.size();
		
		//拆分ojbectList成多个包放到resultList中
		List<List<E>> returnList = new ArrayList<List<E>>();
		List<E> subList = null;
		//不需要分包的情况
		if( listSize <= size  ){
			returnList.add( list );
		}else{
		
			//计算要循环的次数
			int times = listSize/size;
			if(listSize % size > 0){
				times++;
			}
			for(int i=0; i<times; i++){
				subList = new ArrayList<E>();
				for(int n=0; n<size; n++){
					if((j+n) < listSize){
						subList.add(list.get(j+n));
					}else{
						break;
					}
				}
				
				returnList.add(subList);
				j += size;
			}
		}
		
		return returnList;
	}

	/**
	 * Double型的数据转换成非科学计数方式的字符串
	 * @param value
	 * @return
	 */
	public static String Double2String(Double value){
		NumberFormat format = NumberFormat.getInstance();
		format.setGroupingUsed(false);
		return format.format(value);
	}
	
	public static String uuid(){
		return UUID.randomUUID().toString();
	}
	
	public static RichTextJSONMap toRichTextJSONMap(String jsonText){
		RichTextJSONMap resultMap = null;
		try {
			JSON.parseObject(jsonText,  RichTextJSONMap.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return resultMap;
	}
	
	/**
	 * array去重
	 * @param set
	 * @return
	 * @author wxy
	 * @date 2014年9月5日 下午5:06:25
	 */
	public static String[] hashSetToString(String[] targetIds,String[] compareIds){
		//处理共享人的顺序及去重
		Set<String > set = new HashSet<String>();
		if(compareIds!=null){
			for(String id : compareIds){
				set.add(id);
			}
		}
		
		StringBuffer str = new StringBuffer();
		if(targetIds!=null){
			for(String id : targetIds){
				if (!set.contains(id)) {
					str.append(id).append(",");
				}
			}
		}
		
		if(str.length()>0){
			str.deleteCharAt(str.lastIndexOf(","));
		}
			
		return str.toString().split(",");
	}
	
	public static void main(String[] args) {
		String text = "#12345678901";
		System.out.println(isSubPhoneid(text));
	}
}
